<?php
require_once("../../config/config.inc.php");
/***
print_r($_GET);
echo "<br/>post:";
print_r($_POST);
return;
***/
include_once($CFG_REAL_INCLUDES."/jpgraph/jpgraph.php");
include_once($CFG_REAL_INCLUDES."/jpgraph/jpgraph_gantt.php");
/**计算子任务的深度
 */
function calcDepth($iParentID) { 
    global $aTask,$iDepth;       

    if ($iParentID==null || $iParentID==0) {
        $iDepth += 0;
    } else {
        for ($i=0; $i<count($aTask); $i++) {
            if ($aTask[$i][0]==$iParentID) {
                $iDepth += 1;
                $iParentID = $aTask[$i][1]; //
                calcDepth($iParentID);
                break;
            }
        }
    }
    return $iDepth;
}
/**判断该任务是否是大纲
 */
function isPrecis($index) {
    global $aTask;
    $flag = false;
    
    for ($i=$index+1; $i<count($aTask); $i++) {
        if ($aTask[$i][1] == $aTask[$index][0]) { 
            $flag = true;
            break;
        }
    }
    return $flag;
}

//
function CreateGantt($data,$constrains=array(),$progress=array()) {
    global $graph;
    
    for( $i=0; $i < count($data) && count($data[0]) > 0; ++$i) {
        switch( $data[$i][1] ) {
            case ACTYPE_GROUP:
                $a = new GanttBar($data[$i][0],$data[$i][2],$data[$i][3],$data[$i][4],'',0.3); 
                $a->title->SetFont(AR_GANTT_FONT,FS_BOLD,AR_GANTT_SIZE);
                $a->title->setColor('black');        
                $a->rightMark->Show();
                $a->rightMark->SetType(MARK_RIGHTTRIANGLE);
                $a->rightMark->SetWidth(6);
                $a->rightMark->SetColor(AR_GANTT_MASK_COLOR);
                $a->rightMark->SetFillColor(AR_GANTT_MASK_FILLCOLOR);
            
                $a->leftMark->Show();
                $a->leftMark->SetType(MARK_LEFTTRIANGLE);
                $a->leftMark->SetWidth(6);
                $a->leftMark->SetColor(AR_GANTT_MASK_COLOR);
                $a->leftMark->SetFillColor(AR_GANTT_MASK_FILLCOLOR);
            
                $a->SetPattern(BAND_SOLID,AR_GANTT_MASK_BANDCOLOR);

                $n = count($constrains);
                for( $j=0; $j < $n; ++$j ) {
                    if( empty($constrains[$j]) || (count($constrains[$j]) != 3) ) {
                        JpGraphError::Raise("Invalid format for Constrain parameter at index=$j in CreateSimple(). Parameter must start with index 0 and contain arrays of (Row,Constrain-To,Constrain-Type)");  
                    }
                    if( $constrains[$j][0]==$data[$i][0] ) {
                        $a->SetConstrain($constrains[$j][1],$constrains[$j][2],AR_GANTT_CONSTRAIN_COLOR,ARROW_S2,ARROWT_SOLID);    
                        //break;
                    }
                }

                $csimpos = 6;
                break;
            
            case ACTYPE_NORMAL:
                $a = new GanttBar($data[$i][0],$data[$i][2],$data[$i][3],$data[$i][4],'',10);
                $a->title->SetFont(AR_GANTT_FONT,FS_NORMAL,AR_GANTT_SIZE);
                $a->title->setColor('black');
                $a->SetPattern(AR_GANTT_STYLE,AR_GANTT_COLOR);
                $a->SetFillColor(AR_GANTT_BKGCOLOR);
                // Check if this activity should have a constrain line
                $n = count($constrains);
                for( $j=0; $j < $n; ++$j ) {
                    if( empty($constrains[$j]) || (count($constrains[$j]) != 3) ) {
                        JpGraphError::Raise("Invalid format for Constrain parameter at index=$j in CreateSimple(). Parameter must start with index 0 and contain arrays of (Row,Constrain-To,Constrain-Type)");  
                    }
                    if( $constrains[$j][0]==$data[$i][0] ) {
                        $a->SetConstrain($constrains[$j][1],$constrains[$j][2],AR_GANTT_CONSTRAIN_COLOR,ARROW_S2,ARROWT_SOLID);    
                        //break;
                    }
                }

                // Check if this activity have a progress bar
                $n = count($progress);
                for( $j=0; $j < $n; ++$j ) {
                    if( empty($progress[$j]) || (count($progress[$j]) != 2) ) {
                        JpGraphError::Raise("Invalid format for Progress parameter at index=$j in CreateSimple(). Parameter must start with index 0 and contain arrays of (Row,Progress)"); 
                    }
                    if( $progress[$j][0]==$data[$i][0]) {
                        $a->progress->Set($progress[$j][1]);
                        $a->progress->SetPattern(AR_GANTT_PROGRESS_STYLE, AR_GANTT_PROGRESS_COLOR);
                        $a->progress->SetFillColor(AR_GANTT_PROGRESS_BKGCOLOR);
                        //$a->progress->SetPattern($progress[$j][2],$progress[$j][3]);
                        break;
                    }
                }
                $csimpos = 6;
                break;

            case ACTYPE_MILESTONE:
                $a = new MileStone($data[$i][0],$data[$i][2],$data[$i][3]);
                $a->title->SetFont(AR_GANTT_FONT,FS_NORMAL,AR_GANTT_SIZE);
                $csimpos = 5;
                break;
            default:
                die('Unknown activity type');
                break;
        }

        // Setup caption
        $a->caption->Set($data[$i][$csimpos-1]);

        // Check if this activity should have a CSIM target?
        if( !empty($data[$i][$csimpos]) ) {
            $a->SetCSIMTarget($data[$i][$csimpos]);
            $a->SetCSIMAlt($data[$i][$csimpos+1]);
        }
        if( !empty($data[$i][$csimpos+2]) ) {
            $a->title->SetCSIMTarget($data[$i][$csimpos+2]);
            $a->title->SetCSIMAlt($data[$i][$csimpos+3]);
        }

        $graph->Add($a);
    } //end of for loop
}

$sUserID = $SEC->sUserID;
//在用PDF导出时，应该先设置$isGenerateGanttImage = true;并设置$sProjectID变量值，然后include此文件
$sProjectID = $_SESSION["task_project_id"];
if (is_null($sProjectID) || $sProjectID=="") {
	//$sProjectID  = fn_getParam("strProjectID","-1");	
    echo "no project.";
    return false;
}
$sProjectName  = $DB->getFirstField("SELECT PROJECTNAME FROM $TABLE_PROJECT WHERE ID=$sProjectID"); //获取项目名称
//$sUsername   = fn_getParam("strUsername","");
$sScaleType    = fn_getParam("strScaleType","GANTT_HDAY");
$sHourInterval = fn_getParam("strHourInterval","4");
$bSetDateRange = fn_getParam("strDateRange","0"); //have not date range if equal 0
$sStartDate    = fn_getParam("strStartDate","");
$sEndDate      = fn_getParam("strEndDate","");

$aPretask = array(array());	//保存前置任务列表
$aTask    = array(array());	//保存任务列表
$aData    = array(array());	//保存用户绘制甘特图的信息
$aResource = array(array());    //保存任务的资源名称
$aIndex   = 0;

$sql  = "SELECT ID,PARENTID,ORDERNUMB,TASKNAME,PLANSTARTDATE,";
$sql .= "PLANFINISHDATE,FINISHPERCENT,ISMILESTONE ";
$sql .= "FROM $TABLE_TASK WHERE PROJECTID=$sProjectID ";
if ($bSetDateRange == "1") {
    $sql .= "AND (DATE_FORMAT(PLANSTARTDATE,'%Y-%m-%d') >= '".$sStartDate;
    $sql .= "' AND DATE_FORMAT(PLANSTARTDATE,'%Y-%m-%d') <= '".$sEndDate."' OR ";
    $sql .= "DATE_FORMAT(PLANFINISHDATE,'%Y-%m-%d') >= '".$sStartDate;
    $sql .= "' AND DATE_FORMAT(PLANFINISHDATE,'%Y-%m-%d') <= '".$sEndDate."') ";
}
$sql .= "ORDER BY ORDERNUMB";
//echo $sql;return false;
$result = $DB->query($sql);
while ($row = $DB->fetchArray($result)) {	
		$aTask[$aIndex][0] = $row["ID"];
		$aTask[$aIndex][1] = $row["PARENTID"];
		$aTask[$aIndex][2] = $row["ORDERNUMB"];
		$aTask[$aIndex][3] = $row["TASKNAME"];
		//转换时期格式去掉空的时间
		$aTask[$aIndex][4] = fn_fmDatetime($row["PLANSTARTDATE"],"");
		$aTask[$aIndex][5] = fn_fmDatetime($row["PLANFINISHDATE"],"");
	
		$aTask[$aIndex][6] = $row["FINISHPERCENT"];
		$aTask[$aIndex][7] = $row["ISMILESTONE"];	//该任务是否是里程碑，1是，0不是
		$aIndex++;		
}
$DB->freeResult($result);
unset($row);

//获取该项目的资源列表
$sql_res  = "SELECT A.TASKID,A.USERNAME ";
$sql_res .= "FROM $TABLE_TASK_RESOURCE A,$TABLE_TASK B ";
$sql_res .= "WHERE B.PROJECTID='".$sProjectID."' AND A.TASKID=B.ID ";
$sql_res .= "ORDER BY A.TASKID,A.USERNAME";
$res_res  = $DB->query($sql_res);
$aIndex_Res = 0;
while ($rs = $DB->fetchArray($res_res)) {
	$aResource[$aIndex_Res][0] = $rs["TASKID"];   //任务ID
	$aResource[$aIndex_Res][1] = $rs["USERNAME"]; //资源详细名称
	$aIndex_Res++;
}
$DB->freeResult($res_res);

$aIndex2 = 0;
for ($aIndex=0; $aIndex < count($aTask) && count($aTask[0]) > 0; $aIndex++) {
	$iDepth  = 0;
	$sPrefix = str_repeat("  ",calcDepth($aTask[$aIndex][1]));
	$sPrefix = ($aTask[$aIndex][2]<10?"0".$aTask[$aIndex][2]:$aTask[$aIndex][2]).".".$sPrefix;
	$aData[$aIndex][0] = $aIndex;//ACTYPE_GROUP
	$aData[$aIndex][1] = (isPrecis($aIndex)?ACTYPE_GROUP:ACTYPE_NORMAL);	//如果是大纲，则绘制大纲，否则为普通任务
	
	//获取相应的资源名称
	$ResNames = ""; //记录全部资源名称
	for ($i=0; $i<count($aResource)&&count($aResource[0])>0; $i++) {
		if($aTask[$aIndex][0] == $aResource[$i][0]) {
			$ResNames .= (($ResNames=="")?"":",").$aResource[$i][1];
		}
	}
	
	$aData[$aIndex][2] = array($sPrefix.$aTask[$aIndex][3],$ResNames); //用深度值算出前缀字符串，任务的名称和详细名称
	//$aData[$aIndex][2] = $sPrefix.$aTask[$aIndex][3]; //用深度值算出前缀字符串，任务的名称和详细名称
	
	$aData[$aIndex][3] = $aTask[$aIndex][4];
	$aData[$aIndex][4] = $aTask[$aIndex][5];
	//下面为该任务的注释，显示该任务的完成百分比，为空则不显示，有里程碑时也不显示，因为与里程碑的标识重叠;
	if ($aTask[$aIndex][6]>0 && $aTask[$aIndex][7] != "1") 
		$aData[$aIndex][5] = $aTask[$aIndex][6]."%";
	else
		$aData[$aIndex][5] = "";
	//下面加入CSIM MAP热区连接的信息
	$aData[$aIndex][6] = "javascript:maplink(".$aTask[$aIndex][0].");";	//甘特图上热区连接的URL
	$aData[$aIndex][7] = ($aTask[$aIndex][2]<10?"0".$aTask[$aIndex][2]:$aTask[$aIndex][2]).".".$aTask[$aIndex][3];	//甘特图上热区连接的说明
	$aData[$aIndex][8] = $aData[$aIndex][6];	//任务名称上热区连接的URL
	$aData[$aIndex][9] = "";		
}

//获取该项目前置任务列表，Select 当前任务ID和前置任务的序号
$sql  = "SELECT A.TASKID, A.PRETASKID, A.PRETASKTYPE ";
$sql .= "FROM $TABLE_PRETASK A,$TABLE_TASK B ";
$sql .= "WHERE B.PROJECTID=$sProjectID AND A.TASKID=B.ID ";
$sql .= "ORDER BY B.ORDERNUMB";
$res  = $DB->query($sql);
$aIndex=0;
while ($rs = $DB->fetchArray($res)) {
		$aPretask[$aIndex][0] = $rs["TASKID"];
		$aPretask[$aIndex][1] = $rs["PRETASKID"];
		$aPretask[$aIndex][2] = $rs["PRETASKTYPE"];
		$aIndex++;

}
$DB->freeResult($res);
unset($rs);


////下面开始绘制甘特图
define("AR_GANTT_FONT",FF_CHINESE);//FF_CHINESE
define("AR_GANTT_SIZE",10);
define("AR_GANTT_STYLE",GANTT_RDIAG);
define("AR_GANTT_COLOR","yellow");
define("AR_GANTT_BKGCOLOR","red");
define("AR_GANTT_PROGRESS_STYLE",GANTT_SOLID);
define("AR_GANTT_PROGRESS_COLOR","blue");
define("AR_GANTT_PROGRESS_BKGCOLOR","blue");
define("AR_GANTT_MASK_COLOR","black");
define("AR_GANTT_MASK_FILLCOLOR","black");
define("AR_GANTT_MASK_BANDCOLOR","black");
define("AR_GANTT_CONSTRAIN_COLOR","red");
////define the graph scale backcolor
define("SCALE_MONTH_COLOR","#CCCCFF");
define("SCALE_WEEK_COLOR","#C7FED8");
define("SCALE_DAY_COLOR","lightyellow");


$graph = new GanttGraph();
$graph->SetBackgroundGradient('blue@0.8','white',GRAD_HOR,BGRAD_MARGIN);
//$graph->SetMarginColor('lightgreen@0.8');
$graph->SetBox(true,"#0991FF",1.2);
$graph->SetFrame(true,'#0991FF',1.5);

//添加干特图标题
$graph->SetSimpleFont(AR_GANTT_FONT,10); //关键
$graph->title->SetFont(AR_GANTT_FONT,FS_BOLD,12);
$graph->title->Set("<".$sProjectName."> 项目进度甘特图 ".
    "\n(Created By Goodluck4u.com ".date("Y-m-d G:i").")");

//-----------------------  干特图上添加标题（任务名称，资源名称） begin----------------------------------//
//设置干特图上的标题，可以有多个  graph->scale   对应的类是  GanttScale
$graph->scale->actinfo->SetColTitles(array("\n任务名称","\n资源名称"));
$graph->scale->actinfo->SetBackgroundColor('blue:0.8@0.8'); 
//设置标题的背景颜色   scale->actinfo 对应的类是  GanttActivityInfo 
$graph->scale->actinfo->SetFont(AR_GANTT_FONT,FS_NORMAL,10);
//-----------------------  干特图上添加标题（任务名称，资源名称） end ----------------------------------//
$graph->scale->divider->SetWeight(1);
$graph->scale->divider->SetColor("#0991FF");
$graph->scale->dividerh->SetWeight(1);
$graph->scale->dividerh->SetColor("#0991FF");

//set gantt date range
if ($bSetDateRange == "1") {
	$graph->SetDateRange($sStartDate,$sEndDate);
}

//following code is set the graph scale properties, and set scale background color
if ($sScaleType == "GANTT_HYEAR") {
	$graph->ShowHeaders(GANTT_HYEAR);
} 
else if ($sScaleType == "GANTT_HMONTH") {
	$graph->ShowHeaders(GANTT_HYEAR | GANTT_HMONTH);
	$graph->scale->month->SetBackgroundColor(SCALE_MONTH_COLOR); 
} 
else if ($sScaleType == "GANTT_HWEEK") {
	$graph->ShowHeaders(GANTT_HYEAR | GANTT_HMONTH | GANTT_HWEEK);
	$graph->scale->month->SetBackgroundColor(SCALE_MONTH_COLOR); 
	$graph->scale->week->SetBackgroundColor(SCALE_WEEK_COLOR); 
	
	$graph->scale->week->SetStyle(WEEKSTYLE_FIRSTDAYWNBR);
	$graph->scale->SetWeekStart(0);  //week start on sunday
} 
else if ($sScaleType == "GANTT_HDAY") {
	$graph->ShowHeaders(GANTT_HYEAR | GANTT_HMONTH | GANTT_HWEEK | GANTT_HDAY);
	$graph->scale->month->SetBackgroundColor(SCALE_MONTH_COLOR); 
	$graph->scale->week->SetBackgroundColor(SCALE_WEEK_COLOR); 
	$graph->scale->day->SetBackgroundColor(SCALE_DAY_COLOR); 
	
	$graph->scale->SetWeekStart(0);
	$graph->scale->week->SetStyle(WEEKSTYLE_FIRSTDAYWNBR);
} 
else if ($sScaleType == "GANTT_HHOUR") {
	$graph->ShowHeaders(GANTT_HYEAR | GANTT_HMONTH | GANTT_HWEEK | GANTT_HDAY | GANTT_HHOUR);
	$graph->scale->month->SetBackgroundColor(SCALE_MONTH_COLOR); 
	$graph->scale->week->SetBackgroundColor(SCALE_WEEK_COLOR); 
	$graph->scale->day->SetBackgroundColor(SCALE_DAY_COLOR);
	$graph->scale->hour->SetBackgroundColor(SCALE_DAY_COLOR);

	$graph->scale->SetWeekStart(0);
	$graph->scale->week->SetStyle(WEEKSTYLE_FIRSTDAYWNBR); 
	$graph->scale->hour->SetIntervall($sHourInterval);
	$graph->scale->hour->SetStyle(HOURSTYLE_HM24);
}
//end scale properties setting.

//开始绘制前置任务，标明两个任务之间的关系，array(aIndex,aIndex,Contrain_type);
$constrains = array();
$aIndex=0;
for ($i=0; $i < count($aPretask) && count($aPretask[0]) > 0; $i++) {
	for ($j=0; $j < count($aTask) && count($aTask[0]) > 0; $j++) {
		if ($aPretask[$i][0] == $aTask[$j][0]) {	//t_pretasklist.taskid==t_wbs.id
			$iNumb    = $j;			//当前任务在$aTask数组中的位置
			$iPreNumb = -1;			//前置任务在$aTask数组中的位置

			if ($aPretask[$i][2] == "FS") 
				$sTaskType = CONSTRAIN_ENDSTART;
			else if ($aPretask[$i][2] == "SF") 
				$sTaskType = CONSTRAIN_STARTEND;
			else if ($aPretask[$i][2] == "SS") 
				$sTaskType = CONSTRAIN_STARTSTART;
			else if ($aPretask[$i][2] == "FF") 
				$sTaskType = CONSTRAIN_ENDEND;
			else 
				$sTaskType = CONSTRAIN_ENDSTART;

			for ($k=0; $k < count($aTask) && count($aTask[0]) > 0; $k++) {
				if ($aPretask[$i][1] == $aTask[$k][0]) {	//t_pretasklist.preTaskid==t_wbs.id
					$iPreNumb = $k;
					break;
				}
			}
			if ($iPreNumb >= 0) { //存在前置任务，不存在则不用建立
				$constrains[$aIndex] = array($iPreNumb, $iNumb, $sTaskType);
				$aIndex++;
			}
		}
	}
}
//完成
/***
echo "<br>Task:";print_r($aTask);
echo "<br><br>PreTask:";print_r($aPretask);
echo "<br><br>constrains:";print_r($constrains);
echo "<br><br>Resource:";print_r($aResource);
return false;
**/

//标明每一个任务的完成进度，如果完成进度为0，则不标明。array(aIndex,Finish_persent),array(array(3,0.6),array(4,0.8)); 
$progress = array(); 
$aIndex=0;
for ($i=0; $i < count($aTask) && count($aTask[0]) > 0; $i++) {
	if ($aTask[$i][6] > 0) {
		//任务所在数组的位置和任务完成情况，除以100，以小数点的方式显示
		$progress[$aIndex] = array($i,$aTask[$i][6]/100); 
		$aIndex++;
	}
}
//完成

//显示甘特图上的水平表格
$graph->hgrid->Show();
$graph->hgrid->SetRowFillColor('darkblue@0.9');

//创建甘特图
CreateGantt($aData,$constrains,$progress);

//开始绘制甘特图上的里程碑标识
$aIndex=1;
for ($i=0; $i < count($aTask) && count($aTask[0]) > 0; $i++) {
	if ($aTask[$i][7] == "1") {	//1为里程碑
		$sDate = date("Y-m-d",strtotime("+1 day",strtotime($aTask[$i][5])));
		$ms = new MileStone($i,"",$sDate,"");  //"M".$aIndex
		$ms->title->SetFont(AR_GANTT_FONT,FS_NORMAL,AR_GANTT_SIZE);
		$graph->Add($ms);
		$aIndex++;
	}
}
//完成

/**加上logo标识甘特图
$icon = new IconPlot($CFG_REAL_IMAGES."/arouter.jpg",0.016,0.08,0.9,45);
$icon->SetAnchor('left','top');
$graph->Add($icon);
*****/

	$graph->img->SetImgFormat("jpeg");
	if (isset($isGenerateGanttImage) && $isGenerateGanttImage) { //在tmp临时目录下生成甘特图图片文件
		$graph->Stroke($CFG_REAL_TMP."/".$sProjectID.".jpg");
	} else { //发送到客户端进行显示
		//$graph->Stroke();
		$graph->StrokeCSIM("taskGantt.php");
	}

//注销数组
unset($aPretask);
unset($aTask);
unset($aData);
unset($constrains);
unset($progress);
unset($aResource);
?>